package com.company.cloud.club.modules.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.company.cloud.club.modules.core.dto.Result;
import com.company.cloud.club.modules.core.util.DateUtil;
import com.company.cloud.club.modules.core.util.HttpUtils;
import com.company.cloud.club.modules.core.util.ValidateUtil;
import com.company.cloud.club.modules.db.dao.ProductInfoMapper;
import com.company.cloud.club.modules.db.domain.ProductInfo;
import com.company.cloud.club.modules.db.domain.UserInfo;
import com.company.cloud.club.modules.dto.IdQuery;
import com.company.cloud.club.modules.dto.live.LiveBo;
import com.company.cloud.club.modules.service.ClubActivityService;
import com.company.cloud.club.modules.service.CollectionService;
import com.company.cloud.club.modules.service.UserInfoService;
import com.company.cloud.club.modules.utils.GenerateUserSigUtils;
import com.company.cloud.club.modules.utils.LoginContextUtils;
import com.company.cloud.club.modules.vo.LiveInfoVo;
import com.company.cloud.club.modules.vo.ProductVo;
import com.company.cloud.common.auth.annotation.Login;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.*;

/**
 * *****************************************************************************
 * <p>
 * 功能名           ：
 * 系统名           ：
 * <p>
 * *****************************************************************************
 * Modification History
 * <p>
 * Date        Name                    Reason for Change
 * ----------  ----------------------  -----------------------------------------
 * 2020/6/12     zhangxu                 Created
 */
@Slf4j
@RestController
@Api(tags = "直播模块")
@RequestMapping("/live")
public class LiveController {

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private CollectionService collectionService;

    @Autowired
    private ClubActivityService clubActivityService;

    @Autowired
    private ProductInfoMapper productInfoMapper;

    @ApiOperation(value = "获取直播信息")
    @GetMapping(value = "/info")
    public Result getLiveInfo(@Valid @ModelAttribute LiveBo bo) {
        Integer currentUserId = LoginContextUtils.getUserIdOrNotLogin();

        LiveInfoVo vo = new LiveInfoVo();
        UserInfo userInfo = userInfoService.getById(114);
        vo.setNick(userInfo.getNickName());
        vo.setAvatar(userInfo.getHeadImg());
        vo.setFansNum(collectionService.countFunsNum("114"));
        vo.setIsRecom(collectionService.isColled("114", currentUserId));

        // TODO 直播状态 | 直播链接 | IM groupId
        String streamName = bo.getStreamName();
        JSONObject liveObj = getLiveAdmin(streamName);
        if (ValidateUtil.isValid(liveObj)) {
            String state = liveObj.getString("state");
            String time = liveObj.getString("time");
            String backplayUrl = liveObj.getString("backplayUrl");
            if ("回顾".equals(state)) {
                vo.setState("回放");
                if ("artLive001".equals(streamName)) {
                    vo.addBackPlayUrl(backplayUrl);
                    vo.addBackPlayRtmpUrl(backplayUrl);
                } else {
                    clubActivityService.buildBackPlayUrl(vo,  bo.getStreamName());
                }
            } else if ("直播".equals(state)) {
                long liveTime = DateUtil.strToTime(time, "yyyy/MM/dd HH:mm:ss");
                long now = System.currentTimeMillis() / 1000 - 120;
                if (now < liveTime) {
                    vo.setState("未开始");
                } else {
                    vo.setState("直播中");
                    vo.addBackPlayUrl(clubActivityService.getPlayerStream(streamName));
                    vo.addBackPlayRtmpUrl(clubActivityService.getPlayerStreamRtmp(streamName));
                }
            } else {
                vo.setState("已结束");
            }
        } else {
            vo.setState("未开始");
        }

        vo.setGroupId("@TGS#a3KZ5MQHD");
        return Result.ok(vo);
    }

    private JSONObject getLiveAdmin(String currentStreamName) {
        String host = "https://app.artshanghaifair.com";
        String path = "/api/basic-center/app/base/parameter/get?key=live-admin";
        Map<String, String> headers = new HashMap<>();
        Map<String, String> querys = new HashMap<>();
        try {
            HttpResponse httpResponse = HttpUtils.doGet(host, path, "GET", headers, querys);
            String jsonStr = EntityUtils.toString(httpResponse.getEntity());
            JSONObject obj = JSON.parseObject(jsonStr);
            String code = obj.getString("code");
            if ("0".equals(code)) {
                for (Object data : obj.getJSONArray("data")) {
                    JSONObject jsonObj = (JSONObject) data;
                    String streamName = jsonObj.getString("streamName");
                    if (ValidateUtil.isValid(streamName) && streamName.equals(currentStreamName)) {
                        return jsonObj;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private Integer getLiveVisitNum() {
        String host = "https://console.tim.qq.com";
        String path = "/v4/group_open_http_svc/get_online_member_num";
        Map<String, String> headers = new HashMap<>();
        Map<String, String> querys = new HashMap<>();
        querys.put("sdkappid", "1400578220");
        querys.put("identifier", "admin");
        querys.put("usersig", GenerateUserSigUtils.genUserSig("admin"));
        querys.put("random", String.valueOf(new Random().nextInt(100000)));
        querys.put("contenttype", "json");
        Map<String, String> bodys = new HashMap<>();
        bodys.put("GroupId", "@TGS#a3KZ5MQHD");
        try {
            HttpResponse httpResponse = HttpUtils.doPost(host, path, "POST", headers, querys, JSON.toJSONString(bodys));
            String jsonStr = EntityUtils.toString(httpResponse.getEntity());
            JSONObject object = JSON.parseObject(jsonStr);
            if ("OK".equals(object.getString("ActionStatus")) &&
                    object.getInteger("ErrorCode") == 0) {
                return object.getInteger("OnlineMemberNum");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    @ApiOperation(value = "获取直播商品")
    @GetMapping(value = "/product/list")
    public Result getProductList(@Valid @ModelAttribute LiveBo bo) {
        List<ProductVo> productList = new ArrayList<>();
        Set<String> ids = new HashSet<>();
        String streamName = bo.getStreamName();
        JSONObject liveObj = getLiveAdmin(streamName);
        final JSONArray productNos = liveObj.getJSONArray("productNo");
        if(ValidateUtil.isValid(productNos)){
            for (Object productNo:productNos
            ) {
                ids.add(String.valueOf(productNo));
            }
        }

        for (String id : ids) {
            ProductInfo productInfo = productInfoMapper.findByProductNo(id);
            ProductVo vo = new ProductVo();
            vo.setProductNo(productInfo.getProductNo());
            vo.setName(productInfo.getName());
            vo.setImage(productInfo.getImage());
            vo.setMarketPrice(productInfo.getMarketPrice());
            vo.setPrice(productInfo.getPrice());
            productList.add(vo);
        }

        return Result.ok(productList);
    }

    @ApiOperation(value = "获取直播流地址")
    @GetMapping(value = "getLiveStreamAddress")
    public Result getLiveStreamAddress(@Valid @ModelAttribute LiveBo bo) {
        String streamName = bo.getStreamName();
        String liveUrl = clubActivityService.getLiveStream(streamName);
        return Result.ok().msg("生成直播推流").data(liveUrl);
    }

    @ApiOperation(value = "获取播放流地址")
    @GetMapping(value = "getPlayerStreamAddress")
    public Result getPlayerStreamAddress(@Valid @ModelAttribute LiveBo bo) {
        String streamName = bo.getStreamName();
        String playerUrl = clubActivityService.getPlayerStream(streamName);
        return Result.ok().msg("生成播放流地址").data(playerUrl);
    }

    @ApiOperation(value = "IM生成UserSig")
    @GetMapping(value = "genUserSig")
    public Result genUserSig(@Valid @ModelAttribute IdQuery bo) {
        String s = GenerateUserSigUtils.genUserSig(bo.getId());
        return Result.ok(s);
    }

}
